<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

namespace data\formats;

defined('ANS') or die();

class File extends Formats implements iFormats {
	var $format = 'file';

	public function check ($value) {
		$this->error = array();

		if (!$this->checkFile($value[''])) {
			return false;
		}

		return true;
	}

	protected function checkFile ($value, $subformat = '') {
		$settings = $this->settings[$subformat];

		if (!is_array($value)) {
			if ($settings['required'] && (empty($value) || $value == 1)) {
				return false;
			} else {
				return true;
			}
		}

		if ($value['error']) {
			switch ($value['error']) {
				case 1:
					$this->error[$subformat] = __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
					return false;
				case 2:
					$this->error[$subformat] = __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
					return false;
				case 3:
					$this->error[$subformat] = __('The uploaded file was only partially uploaded.');
					return false;
				case 6:
					$this->error[$subformat] = __('Missing a temporary folder.');
					return false;
				case 7:
					$this->error[$subformat] = __('Failed to write file to disk.');
					return false;
				case 8:
					$this->error[$subformat] = __('File upload stopped by extension.');
					return false;
			}
		}

		if (!$settings['required'] && ($value['size'] == 0)) {
			return true;
		}

		if ($settings['required'] && ($value['size'] == 0)) {
			$this->error[$subformat] = __('This field can not be empty');

			return false;
		}

		$path = $settings['base_path'].$settings['uploads'].$settings['subfolder'];

		if (!is_dir($path)) {
			$File = new \files\File;

			if (!$File->makeFolder($path)) {
				$this->error[$subformat] = __('The folder to store the file haven\'t writing permissions');
				return false;
			}
		} else if (!is_writable($path)) {
			$this->error[$subformat] = __('The folder to store the file haven\'t writing permissions');
			return false;
		}

		if (!($ext = strtolower(pathinfo($value['name'], PATHINFO_EXTENSION)))) {
			$ext = end(explode('/', finfo_file($value['tmp_name']), 2));
		}

		if ($settings['mime_types']) {
			$File = new \files\File;

			if (!$File->getMimeType($value['tmp_name'], $settings['mime_types'])) {
				$this->error[$subformat] = __('This file has an invalid format');
				return false;
			}
		}

		return true;
	}

	public function valueDB (\data\Data $Data, $value, $language = '', $id = 0) {
		$result = $this->saveFile($value[''], $id);

		if (is_array($result) || $result === false) {
			return $result;
		}

		return array('' => $this->settings['']['subfolder'].$result);
	}


	protected function saveFile ($value, $id, $subformat = '') {
		$settings = $this->settings[$subformat];

		//If the file doesn't exits
		if (!$value || $value == 1 || (is_array($value) && ($value['size'] == 0 || !is_file($value['tmp_name'])))) {
			if ($id) {
				if ($value == 1) {
					if ($settings['default']) {
						return array($subformat => $settings['default']);
					} else {
						return array($subformat => '');
					}
				} else {
					return false;
				}
			} else {
				if ($settings['default']) {
					return array($subformat => $settings['default']);
				} else {
					return false;
				}
			}
		}

		if (is_string($value) && !strstr($value, '://')) {
			return array($subformat => $value);
		}

		if (is_array($value)) {
			$name = $value['name'];
			$realfile = $value['tmp_name'];
		} else {
			$name = $realfile = $value;
		}

		//Save file
		$File = new \files\File;

		if (!($saved_file_name = $File->save($value, $settings['base_path'].$settings['uploads'].$settings['subfolder'], uniqid()))) {
			$this->error[$subformat] = __('Error storing the new file');
			return false;
		}

		return preg_replace('#^'.$settings['base_path'].$settings['uploads'].$settings['subfolder'].'#', '', $saved_file_name);
	}

	public function afterSave (\data\Data $Data, $values) {
		if ($values['old_value'][''] && ($values['new_value'][''] == 1 || ($values['new_value'][''] != $values['old_value']['']))) {
			$old_file = $this->settings['']['base_path'].$this->settings['']['uploads'].$values['old_value'][''];

			if (is_file($old_file)) {
				unlink($old_file);
			}
		}

		return true;
	}

	public function settings ($settings) {
		global $Config;

		$this->bindEvent(array('afterUpdate', 'afterDelete'), array($this, 'afterSave'));

		$this->settings = $this->setSettings($settings, array(
			'' => array(
				'db_type' => 'varchar',

				'length_max' => 250,
				'max_size' => intval(ini_get('upload_max_filesize')),
				'valid_extensions' => array(),
				'base_path' => SCENE_PATH,
				'uploads' => $Config->scene_paths['uploads'],
				'subfolder' => $this->table.'/'.$this->name.'/'
			)
		));

		return $this->settings;
	}
}
?>
